package com.fysports.web.kit.commons;

import com.google.common.io.Files;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.fysports.framework.exception.FrameException;
import com.fysports.web.config.AppConst;
import com.fysports.web.kit.umeditor.DownLoadFileParse;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.Date;


/**
 * 文件操作工具类
 * Created by konbluesky
 * Date : 14-8-24 下午12:43
 * Project : JdmData_WebServer
 */
public class FileKit extends com.jfinal.kit.FileKit {
    private static Log logger = Log.getLog(FileKit.class);
    private final static String DEF_BIAOZHI = "upload";


    public static void copyFile(File srcFile, File dest) throws IOException {
        if (srcFile == null || dest == null) {
            throw new IllegalArgumentException("copy源文件或者目标文件无效，请查验");
        }
        FileUtils.copyFile(srcFile, dest);
    }


    public static String saveFileForReal(File sfile, String biaozhi, String bizuuid) throws Exception {
        return saveFileForType(AppConst.UPLOAD_REALPATH, sfile, biaozhi, bizuuid);
    }


    public static String saveFileForTmp(File sfile, String biaozhi, String bizuuid) throws Exception {
        return saveFileForType(AppConst.UPLOAD_TMPPATH, sfile, biaozhi, bizuuid);
    }


    /**
     * 保存文件到系统文件目录
     * path:/标志/文件名.后缀
     *
     * @param type    AppConst.UPLOAD_TMPPATH  | AppConst.UPLOAD_REALPATH
     * @param sfile   源文件
     * @param biaozhi 标志
     * @param bizuuid 传业务UUID
     * return 返回新文件名;
     * @throws Exception
     */
    public static String saveFileForType(String type, File sfile, String biaozhi, String bizuuid)
            throws Exception {
        //生成业务目录 //path/module/bizuuid/timestamp.ext
        String path = getPath(type, biaozhi , bizuuid);
        String filename = "";
        try {
            if (!StringKit.isBlank(bizuuid)) {
                String timestamp=DateTimeKit.format(new Date(),"yyMMddHHmmssS");
                filename = timestamp + getFileExt(sfile.getName());
                path += File.separator + filename;
            }
            copyFile(sfile, new File(path));
        }
        catch (Exception e) {
            logger.error(filename + ":文件保存失败", e);
            throw e;
        }
        return filename;
    }

    /**
     * 获取u路径
     * /biaozhi/
     *
     * @param type AppConst.UPLOAD_TMPPATH  | AppConst.UPLOAD_REALPATH
     * @return
     */
    private static String getPath(String type, String biaozhi,String bizuuid) throws Exception {
        String path = PropKit.use(AppConst.CONFIG_SYSTEM).get(type);
        try {
            if (biaozhi == null || biaozhi.length() == 0) {
                biaozhi = DEF_BIAOZHI;
            }
            path = getFolder(path + File.separator + biaozhi + File.separator + bizuuid);
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            logger.error("", e);
            throw e;
        }
        return path;
    }


    /**
     * 将临时文件目录，移到真实目录下
     * 传入modulename/bizuuid/abcde.jpg
     *
     * @param name
     */
    public static void moveTmpToReal(String name) {
        String temp_path = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.UPLOAD_TMPPATH);
        String real_path = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.UPLOAD_REALPATH);
        //保存文件到系统文件夹
        File tmp_dir = new File(temp_path + File.separator + name);
        File real_file = new File(real_path + File.separator + name);
        if (!tmp_dir.exists() ) {
            try {
                Files.createParentDirs(tmp_dir);
            }
            catch (IOException e) {
                logger.error(e.getLocalizedMessage(),e);
            }
        }
        if(!real_file.exists()){
            try {
                Files.createParentDirs(real_file);
            }
            catch (IOException e) {
                logger.error(e.getLocalizedMessage(),e);
            }
        }
        try {
            copyFolder(tmp_dir,real_file);
        }
        catch (IOException e) {
            logger.error(e.getLocalizedMessage(),e);
            String t_u=tmp_dir.getPath();
            String d_u=tmp_dir.getPath();
            throw new FrameException("文件复制出错:源文件->"+t_u+"\r目标文件->"+d_u,e);
        }
    }


    /**
     * v0.2 取消在path下生成当前日期文件夹操作,直接以业务UUID创建文件夹
     * v0.1 根据字符串创建本地目录 并按照日期建立子目录返回
     * @param path
     * @return
     */
    private static String getFolder(String path) throws Exception {
        File dir = new File(path);
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            }
            catch (Exception e) {
                logger.error(path + ":默认目录创建失败(getFolder)", e);
                throw e;
            }
        }
        return path;
    }


    /**
     * 根据UmeditorHandlerFileUrl 获取下载图片的真实地址
     *
     * @param ehf
     * @return
     */
    public static String getFileNameByUME(DownLoadFileParse ehf) {
        String path = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.UPLOAD_REALPATH);
        path += ehf.getHttpUrl();
        return path;
    }


    /**
     * 获取文件扩展名
     *
     * @return string
     */
    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }


    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     * @param src
     * @param dest
     * @throws IOException
     */
    private static void copyFolder(File src, File dest) throws IOException {
        if(src==null||!src.exists())return ;

        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String files[] = src.list();
            for (String file : files) {
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                // 递归复制
                copyFolder(srcFile, destFile);
            }
        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        }
    }

    /**
     * 返回/module/uuid
     * @param module
     * @param uuid
     */
    public static String getDiretory(String module,String uuid){
        StringBuilder sb=new StringBuilder(File.separator);
        sb.append(module);
        sb.append(File.separator);
        sb.append(uuid);
        return sb.toString();
    }


    public static void main(String[] s) {
        File f = null;
        try {
            FileUtils.write(f = new File("/tmp/luxcon/a.txt"), "asdfasdfasdfasdf");
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        //        System.out.println(new FileKit().getFileExt("asdfasdfasdf.jpb"));
        //        System.out.println(new File("/tmp/luxcon/a.txt").getName());
        //        System.out.println("getAbsolutePath:" + f.getAbsolutePath());
        //        System.out.println("getPath:"+f.getPath());
        //        System.out.println("getParent:"+f.getParent());

        //        FileKit.saveFileForType(AppConst.UPLOAD_REALPATH,f,null,true);
        //        FileKit.saveFileForType(AppConst.UPLOAD_REALPATH,f,null,false);
        //        FileKit.saveFileForType(AppConst.UPLOAD_TMPPATH,f, null, true);
        //        FileKit.saveFileForType(AppConst.UPLOAD_TMPPATH,f, null, false);

    }

}
